﻿using Engine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Game.Server;
using Game.Server.Plugins;
using System.Globalization;

namespace Game
{
    public class CmdCloudSpace : AbstractProcessCmd
    {
        public override string Cmd => "c";

        public override string Introduce => "/c  -查看云背包指令";

        public override int AuthLevel => 0;

        public override DisplayType Display => DisplayType.All;

        public override void ProcessCmd()
        {
            if (GameManager.Project == null) return;
            if (m_isTerminal == true)
            {
                SendMessage(Cmd, "控制台不能使用");
                return;
            }
            if (m_client.PlayerData.ComponentPlayer == null)
            {
                SendMessage(Cmd, "玩家组件不存在，无法使用");
                return;
            }
            if (m_messageDatas.Length == 2)
            {
                if(m_messageDatas[1] == "查看" || m_messageDatas[1] == "show")
                {
                    if (CloudSpacePlugin.CloudItems.TryGetValue(m_client.CommunityAccountId, out Dictionary <int,int> items))
                    {
                        if(items != null && items.Count != 0)
                        {
                            for (int k = 0; k < items.Count; k++)
                            {
                                int v = items.ElementAt(k).Key;
                                int c = items.ElementAt(k).Value;
                                if(c == 0)
                                {
                                    CloudSpacePlugin.CloudItems[m_client.CommunityAccountId].Remove(v);
                                }
                            }
                        }
                    }
                    if (CloudSpacePlugin.CloudItems.TryGetValue(m_client.CommunityAccountId, out Dictionary<int, int> items2))
                    {
                        if (items2 != null && items2.Count != 0)
                        {
                            SubsystemTerrain subsystemTerrain = GameManager.Project.FindSubsystem<SubsystemTerrain>();
                            string show = string.Empty;
                            for (int k = 0; k < items2.Count; k++)
                            {
                                int v = items2.ElementAt(k).Key;
                                int c = items2.ElementAt(k).Value;
                                string name = BlocksManager.Blocks[Terrain.ExtractContents(v)].GetDisplayName(subsystemTerrain, v);
                                show += $"序号:{k} 物品:{name} 数量:{c} 方块值:{v}\n";
                            }
                            SendMessage(Cmd, "查看你的物品：\n" + show);
                        }
                        else
                        {
                            SendMessage(Cmd, "没有物品存放在云背包");
                        }
                    }
                    else
                    {
                        SendMessage(Cmd, "没有物品存放在云背包");
                    }
                }
                else if(m_messageDatas[1] == "保存" || m_messageDatas[1] == "save")
                {
                    ComponentCraftingTable componentCraftingTable = m_client.PlayerData.ComponentPlayer.Entity.FindComponent<ComponentCraftingTable>();
                    if(componentCraftingTable != null)
                    {
                        for(int i = 0; i < componentCraftingTable.SlotsCount; i++)
                        {
                            int v = componentCraftingTable.GetSlotValue(i);
                            int c = componentCraftingTable.GetSlotCount(i);
                            if(Terrain.ExtractContents(v) != 0 && c != 0)
                            {
                                if (!CloudSpacePlugin.CloudItems.TryGetValue(m_client.CommunityAccountId, out Dictionary<int, int> items3))
                                {
                                    CloudSpacePlugin.CloudItems[m_client.CommunityAccountId] = new Dictionary<int, int>();
                                    items3 = CloudSpacePlugin.CloudItems[m_client.CommunityAccountId];
                                }
                                if (items3.ContainsKey(v))
                                {
                                    items3[v] += c;
                                }
                                else
                                {
                                    items3[v] = c;
                                }
                                componentCraftingTable.RemoveSlotItems(i, c);
                            }
                        }
                        SendMessage(Cmd, "成功将合成台物品存放到云背包");
                    }
                    else
                    {
                        SendMessage(Cmd, "找不到工作台组件");
                    }
                }
                else
                {
                    if(int.TryParse(m_messageDatas[1], out int i))
                    {
                        if (CloudSpacePlugin.CloudItems.TryGetValue(m_client.CommunityAccountId, out Dictionary<int, int> items4))
                        {
                            if(items4 != null && items4.Count > 0 && i < items4.Count)
                            {
                                int v = items4.ElementAt(i).Key;
                                int c = items4.ElementAt(i).Value;
                                if(c > 0)
                                {
                                    SubsystemPickables subsystemPickables = GameManager.Project.FindSubsystem<SubsystemPickables>();
                                    subsystemPickables.AddPickable(v, c, m_client.PlayerData.ComponentPlayer.ComponentBody.Position, null, null);
                                    items4[v] = 0;
                                }
                                else
                                {
                                    SendMessage(Cmd, "你的云背包找不到指定物品，请检查云背包物品");
                                }
                            }
                            else
                            {
                                SendMessage(Cmd, "你的云背包找不到指定物品，请检查云背包物品");
                            }
                        }
                        else
                        {
                            SendMessage(Cmd, "你的云背包找不到指定物品，请检查云背包物品");
                        }
                    }
                    else
                    {
                        SendMessage(Cmd, "输入的指令有误，请重试");
                    }
                }
            }
            else if (m_messageDatas.Length == 3)
            {
                try
                {
                    int i = int.Parse(m_messageDatas[1]);
                    int n = int.Parse(m_messageDatas[2]);
                    if (CloudSpacePlugin.CloudItems.TryGetValue(m_client.CommunityAccountId, out Dictionary<int, int> items5))
                    {
                        if (items5 != null && items5.Count != 0)
                        {
                            int v = items5.ElementAt(i).Key;
                            int c = items5.ElementAt(i).Value;
                            if (c > 0)
                            {
                                if (n > c) n = c;
                                SubsystemPickables subsystemPickables = GameManager.Project.FindSubsystem<SubsystemPickables>();
                                subsystemPickables.AddPickable(v, n, m_client.PlayerData.ComponentPlayer.ComponentBody.Position, null, null);
                                items5[v] = items5[v] - n;
                            }
                            else
                            {
                                SendMessage(Cmd, "你的云背包找不到指定物品，请检查云背包物品");
                            }
                        }
                        else
                        {
                            SendMessage(Cmd, "你的云背包找不到指定物品，请检查云背包物品");
                        }
                    }
                    else
                    {
                        SendMessage(Cmd, "你的云背包找不到指定物品，请检查云背包物品");
                    }
                }
                catch
                {
                    SendMessage(Cmd, "输入的指令有误，请重试");
                }
            }
            else
            {
                string help = "/c i   -取出序号为i的物品\n";
                help += "/c i n   -取出n个序号为i的物品\n";
                help += "/c 查看   -查看云背包物品\n";
                help += "/c 保存   -将自带合成台的物品存入云背包\n";
                help += "/c show   -查看云背包物品\n";
                help += "/c save   -将自带合成台的物品存入云背包\n";
                SendMessage(Cmd, help);
            }
        }
    }

    public class CloudSpacePlugin : ServerPlugin
    {
        public override string Name => "云背包插件";

        public override int Version => 10000;

        public byte FirstLevel => 0;

        public static string CloudSpacePath;

        public static Dictionary<string, Dictionary<int, int>> CloudItems = new Dictionary<string, Dictionary<int, int>>();

        public override void Initialize()
        {
        }

        public string GetPluginDataByWorldPath(string fileName)
        {
            string pluginDataPath = Storage.GetSystemPath("app:/PluginData");
            if (!Directory.Exists(pluginDataPath))
            {
                Directory.CreateDirectory(pluginDataPath);
            }
            string worldName = GameManager.Project.FindSubsystem<SubsystemGameInfo>().WorldSettings.Name;
            string dataByWorldPath = Storage.CombinePaths(pluginDataPath, worldName);
            if (!Directory.Exists(dataByWorldPath))
            {
                Directory.CreateDirectory(dataByWorldPath);
            }
            return Storage.CombinePaths(dataByWorldPath, fileName);
        }

        public override void Load()
        {
            CloudSpacePath = GetPluginDataByWorldPath("CloudSpace.json"); 
            try
            {
                CloudItems.Clear();
                if (File.Exists(CloudSpacePath))
                {
                    using (StreamReader file = File.OpenText(CloudSpacePath))
                    {
                        string jsonText = file.ReadToEnd();
                        CloudItems = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<int, int>>>(jsonText);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error($"插件{Name}装载失败：{e.Message}");
            }
        }

        public override void Save()
        {
            try
            {
                string jsonText = JsonConvert.SerializeObject(CloudItems);
                using (FileStream fileStream = File.Open(CloudSpacePath, FileMode.Create))
                {
                    using (StreamWriter fileWrite = new StreamWriter(fileStream))
                    {
                        fileWrite.Write(jsonText);
                        fileWrite.Flush();
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error($"插件{Name}保存失败：{e.Message}");
            }
        }
    }
}